//
//  CWCSearchViewController.m
//  ChuanNews
//
//  Created by dllo on 16/4/26.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "CWCSearchViewController.h"
#import "BaseHeader.h"
@interface CWCSearchViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>
@property(nonatomic, retain)UITableView *tableView;
@property(nonatomic, retain)NSMutableArray *array;
@property(nonatomic, retain)NSString *keyWord;
@property(nonatomic, retain)UISearchBar *searchBar;
@property(nonatomic, retain)UIView *beginView;
@property(nonatomic, retain)UIScrollView *hotWordView;
@property(nonatomic, assign)CGFloat maxRight;
@property(nonatomic, assign)CGFloat maxBottom;
@property(nonatomic, assign)NSArray *hotWordArray;

@end

@implementation CWCSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.array = [NSMutableArray array];
    [self creatView];
    
}

-(void)creatView{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.rowHeight = 80;
    [self.tableView registerClass:[CWCSearchCell class] forCellReuseIdentifier:@"cell"];
    
    UIView *searchView = [[UIView alloc]initWithFrame:CGRectMake(90, 23, WIDTH - 100, 35)];
    self.searchBar = [[UISearchBar alloc]init];
    self.searchBar.delegate = self;
    self.searchBar.frame = CGRectMake(0, 0, WIDTH - 100, 28);
    self.searchBar.layer.cornerRadius = 14;
    self.searchBar.placeholder = @"搜索新闻,文章,图片                                         ";
    self.searchBar.layer.masksToBounds = YES;
    [searchView  addSubview:self.searchBar];
    self.searchBar.backgroundColor = [UIColor whiteColor];
    self.navigationItem.titleView = searchView;
    
    self.beginView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH , HEIGHT)];
    [self.tableView addSubview:self.beginView];
    
    UILabel *hotWordLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, 20, 60, 60)];
    hotWordLabel.text = @"近期热点";
    hotWordLabel.font = [UIFont systemFontOfSize:14];
    hotWordLabel.textAlignment = 1;
    [self.beginView addSubview:hotWordLabel];
    
    self.hotWordView = [[UIScrollView alloc]initWithFrame:CGRectMake(20, 50, WIDTH - 40, HEIGHT - 100)];
    [self.beginView addSubview:self.hotWordView];
    self.hotWordView.bounces = YES;
    self.maxRight = 0;
    self.maxBottom = 10;
    self.hotWordView.contentSize = self.hotWordView.frame.size;
    self.hotWordView.showsHorizontalScrollIndicator = NO;
    self.hotWordView.showsVerticalScrollIndicator = NO;
    
    if (self.keyWord.length > 0) {
        self.searchBar.text = self.keyWord;
        [self searchBarSearchButtonClicked:self.searchBar];
    }
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:@"http://c.3g.163.com/nc/search/hotWord.html" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = responseObject;
        self.hotWordArray = dic[@"hotWordList"];
        
        for (NSDictionary *dict in self.hotWordArray) {
            [self addKeyWordWithTitle:dict[@"hotWord"]];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    
    }];
   
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [searchBar resignFirstResponder];
    NSString *searchWord = [searchBar.text base64encode];
    NSString *url = [NSString stringWithFormat:@"http://c.3g.163.com/search/comp/MA==/20/%@.html",searchWord];
    NSLog(@"%@", url);
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = responseObject;
        NSArray *dicArray = dic[@"doc"][@"result"];
        for (NSDictionary *dic in dicArray) {
            NSLog(@"%@", dic);
            CWCSearchModel *model = [[CWCSearchModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.array addObject:model];
            NSLog(@"%@", self.array);
        }
        [self.tableView reloadData];
        self.beginView.hidden = YES;
        self.tableView.hidden = NO;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"%@",error);
    }];
    
    
}

-(void)addKeyWordWithTitle:(NSString *)title{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake(self.maxRight, self.maxBottom, 0, 0);
    [button setTitle:title forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:15];
    button.layer.borderWidth = 0.5;
    button.layer.borderColor = [UIColor grayColor].CGColor;
    button.layer.cornerRadius = 2;
    button.layer.masksToBounds = YES;
    [button sizeToFit];
    button.width += 15;
    button.height = 34;
    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.hotWordView addSubview:button];
    self.maxRight = button.width + button.x + 10;
    if (self.maxRight > self.hotWordView.width) {
        self.maxRight = 0;
        self.maxBottom += 48;
        button.x = self.maxRight;
        button.y = self.maxBottom;
        self.maxRight = button.width + button.x + 10;
    }
}

-(void)buttonClick:(UIButton *)button{
    self.searchBar.text = button.titleLabel.text;
    [self searchBarSearchButtonClicked:self.searchBar];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.array.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CWCSearchModel *model = self.array[indexPath.row];
    CWCSearchCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    NSMutableString *string = [model.title mutableCopy];
    [string replaceOccurrencesOfString:@"<em>" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, string.length)];
    [string replaceOccurrencesOfString:@"</em>" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, string.length)];
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc]initWithString:string];
    NSRange range = [string rangeOfString:self.searchBar.text];
    [attributeString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
    [attributeString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:19] range:range];
    cell.titleLabel.attributedText = attributeString;
    cell.timeLabel.text = model.ptime;
    return cell;
}-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    CWCSearchModel *model = self.array[indexPath.row];
    CWCDetailReadingViewController *vc = [[CWCDetailReadingViewController alloc]init];
    vc.reading = model;
    vc.id = model.docid;
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}



-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    if (searchText.length < 1) {
        self.tableView.hidden = YES;
        self.beginView.hidden = NO;
    }
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
